package com.wangyf.thread.c_014_latch_join;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * CountDownLatch是一个同步的辅助类，允许一个或多个线程，等待其他一组线程完成操作，再继续执行。
 * 测试: CountDownLatch
 * CountDown 倒数 Latch 门栓
 * 倒数为0的时候才可以运行
 * @author wangyf
 * @date 2021/1/4 11:48
 * 一个典型应用场景就是启动一个服务时，主线程需要等待多个组件加载完毕，之后再继续执行。
 */
public class CountDownLatchTest {


    public static void main(String[] args) {
        CountDownLatchTest c = new CountDownLatchTest();
        c.testCountDownLatch();
        c.testJoin();
    }
    // 倒数
    void testCountDownLatch() {
        Thread[] threads = new Thread[100];
        CountDownLatch countDownLatch = new CountDownLatch(threads.length);
        for (int i = 0; i < 100; i++) {// countDown调用次数 必须和 构造方法的值相同，小于会将调用await()的线程一直阻塞，超了汇报数组越界
            Thread thread = new Thread(() -> {
                int sum = 0;
                for (int j = 0; j < 100000; j++) {
                    sum+=j;
                }
                countDownLatch.countDown();
            });
            threads[i] = thread;
        }
        for (Thread thread : threads) {
            if (thread != null)
            thread.start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("testCountDownLatch end");
    }
    void testJoin() {
        Thread[] threads = new Thread[100];
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            threads[i] = thread;
        }
        for (Thread thread : threads) {
            thread.start();

        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("testJoin end");
    }
}
